var api = require('utils/api.js');
//app.js
App({
  //cb = callback
  getUserInfo: function(cb, force) {
    let that = this,
      this_version = 1.30;

    // 如果更新版本就清空所有缓存，免得有后患

    if (wx.getStorageSync('version') && wx.getStorageSync('version') != this_version) {
      wx.clearStorageSync();
    }
    wx.setStorageSync('version', this_version);

    // token丢了,过期或没登录

    if (!wx.getStorageSync('token') || force == true) {
      // 如果上次授权时间没超过五分钟

      // 此单位为秒, 5分钟

      if ((Math.round(new Date().getTime() / 1000) - wx.getStorageSync('last_getUserInfo_failTime')) < 300) {
        that.loginFail(cb);
      } else {
        that.login(cb);
      }
    } else {
      //回调

      cb && cb()
    }
  },
  login: function(cb) {
    var that = this;
    //等待动画走起
    wx.showToast({
      title: '正在登录...',
      icon: 'loading',
      duration: 10000
    });
    wx.login({
      success: function(res) {
        var code = res.code;
        wx.getUserInfo({
          success: function(res2) {
            //要把加密串转成URI编码
            var encryptedData = encodeURIComponent(res2.encryptedData);
            var iv = res2.iv;
            var url = api.getApiUrl() + '/wechat/login';
            //请求服务器
            wx.request({
              url: url,
              data: {
                code: code,
                encryptedData: encryptedData,
                iv: iv,
                type: 'h1z1'
              },
              method: 'GET',
              header: {
                'content-type': 'application/json'
              },
              success: function(res) {
                console.log(res)
                //返回的token和user_id（当前用户id，仅用作前端判断）要保存
                wx.setStorageSync('token', res.data.datas.token);
                wx.setStorageSync('user_id', res.data.datas.userId);

                //回调
                if (cb) {
                  cb();
                }
              }
            })
          },
          fail: function() {
            console.log('fail')
            that.loginFail(cb);
          },
          complete: function() {
            //关闭等待动画
            wx.hideToast();
          }
        })
      }
    })

  },
  loginFail: function(cb) {
    wx.showModal({
      title: '提示',
      content: '无法从微信获取您的身份标识，程序无法正常使用。请五分钟后重新打开本程序。',
      showCancel: false,
      success: function(res) {
        if (res.confirm) {
          //记录最后一次拒绝获取用户信息的操作时间
          wx.setStorageSync('last_getUserInfo_failTime', Math.round(new Date().getTime() / 1000));

          setTimeout(function() {
            if (cb) {
              that.getUserInfo(cb);
            } else {
              that.getUserInfo();
            }

          }, 5 * 60 * 1000);
        }
      }
    })
  },
  onLaunch: function(ops) {
    // 登录
    // this.getUserInfo();
    // 判断场景值是否为转发到群聊
    wx.setStorageSync('scene', ops.scene);
    if (ops.scene == 1044) {
      wx.getShareInfo({
        shareTicket: ops.shareTicket,
        complete(res) {
          wx.setStorageSync('encryptedData', res.encryptedData);
          wx.setStorageSync('iv', res.iv);
          console.log(wx.getStorageSync('iv'))
        }
      })
    }
  }
})